﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;

namespace SetIEProxy
{
    public partial class Form1 : Form
    {
        #region Attributes

        private static QT.IO.INIFile ProxyFile = new QT.IO.INIFile(GlobalAttrib.IniPath);
        private const int INTERNET_OPTION_SETTINGS_CHANGED = 37;
        private const int INTERNET_OPTION_REFRESH = 39;

        //下面是可用的常量，根据不同的动画效果声明自己需要的  
        private const int AW_HOR_POSITIVE = 0x0001;//自左向右显示窗口，该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志  
        private const int AW_HOR_NEGATIVE = 0x0002;//自右向左显示窗口，该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志  
        private const int AW_VER_POSITIVE = 0x0004;//自顶向下显示窗口，该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志  
        private const int AW_VER_NEGATIVE = 0x0008;//自下向上显示窗口，该标志可以在滚动动画和滑动动画中使用。使用AW_CENTER标志时忽略该标志该标志  
        private const int AW_CENTER = 0x0010;//若使用了AW_HIDE标志，则使窗口向内重叠；否则向外扩展  
        private const int AW_HIDE = 0x10000;//隐藏窗口  
        private const int AW_ACTIVE = 0x20000;//激活窗口，在使用了AW_HIDE标志后不要使用这个标志  
        private const int AW_SLIDE = 0x40000;//使用滑动类型动画效果，默认为滚动动画类型，当使用AW_CENTER标志时，这个标志就被忽略  
        private const int AW_BLEND = 0x80000;//使用淡入淡出效果  

        #endregion

        #region Form

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (!File.Exists(GlobalAttrib.IniPath))
            {
                if (MessageBox.Show("您还没有设置代理服务器,是否现在设置?", "友情提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
                {
                    Option Option = new Option();
                    Option.ShowInTaskbar = false;
                    Option.ShowDialog();
                }
                else
                {
                    MessageBox.Show("代理未配置，程序退出");
                    Application.ExitThread();
                    return;
                }
            }

            ShowProxy();
            InitForm();

            //int x = Screen.PrimaryScreen.WorkingArea.Right - this.Width;
            //int y = Screen.PrimaryScreen.WorkingArea.Bottom - this.Height;
            //this.Location = new Point(x, y);//设置窗体在屏幕右下角显示  
            SafeNativeMethods.AnimateWindow(this.Handle, 2000, AW_BLEND); 
        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.notifyIcon1.Visible = true;
                this.Hide();
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            if (MessageBox.Show("确认要退出吗?", "友情提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                e.Cancel = false;
                SafeNativeMethods.AnimateWindow(this.Handle, 2000, AW_SLIDE | AW_BLEND | AW_HIDE);  
            }
        }

        #endregion

        #region Button

        private void btnTeleCom_Click(object sender, EventArgs e)
        {
            string ProxyServer;
            string ProxyPort;

            if (!ProxyFile.ReadInivalue("TelCom", "Server", out ProxyServer))
            {
                MessageBox.Show("读取配置文件失败");
                return;
            }
            if (!ProxyFile.ReadInivalue("TelCom", "Port", out ProxyPort))
            {
                MessageBox.Show("读取配置文件失败");
                return;
            }

            if (!ReadProxy(ProxyServer + ":" + ProxyPort))
            {
                SetProxy(ProxyServer + ":" + ProxyPort);
            }
            else
            {
                CloseProxy();
            }

            ShowProxy();
            InitForm();
        }

        private void btnUniCom_Click(object sender, EventArgs e)
        {
            string ProxyServer;
            string ProxyPort;

            if (!ProxyFile.ReadInivalue("UniCom", "Server", out ProxyServer))
            {
                MessageBox.Show("读取配置文件失败");
                return;
            }
            if (!ProxyFile.ReadInivalue("UniCom", "Port", out ProxyPort))
            {
                MessageBox.Show("读取配置文件失败");
                return;
            }

            if (!ReadProxy(ProxyServer + ":" + ProxyPort))
            {
                SetProxy(ProxyServer + ":" + ProxyPort);
            }
            else
            {
                CloseProxy();
            }

            ShowProxy();
            InitForm();
        }

        #endregion

        #region ProxySetting

        private void SetProxy(string Server)
        {
            //打开注册表
            RegistryKey regKey = Registry.CurrentUser;
            string SubKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
            RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);
            if (optionKey == null)
            {
                MessageBox.Show(@"注册表损坏，请修复\nHKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings");
                return;
            }

            //更改健值，设置代理，
            try
            {
                optionKey.SetValue("ProxyEnable", 1);
                optionKey.SetValue("ProxyServer", Server);
                optionKey.SetValue("ProxyOverride", string.IsNullOrEmpty(GlobalAttrib.Filters) ? "<local>" : (GlobalAttrib.Filters + ";<local>"));
                optionKey.SetValue("DisablePasswordCaching", 0);
            }
            catch
            {
                MessageBox.Show("代理设置失败");
                return;
            }

            //激活代理设置
            try
            {
                SafeNativeMethods.InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
                SafeNativeMethods.InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
            }
            catch
            {
                MessageBox.Show("代理激活失败");
                return;
            }
        }

        private void CloseProxy()
        {
            //打开注册表
            RegistryKey regKey = Registry.CurrentUser;
            string SubKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
            RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);
            if (optionKey == null)
            {
                MessageBox.Show(@"注册表损坏，请修复\nHKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings");
                return;
            }

            //更改健值，设置代理
            try
            {
                optionKey.SetValue("ProxyEnable", 0);
            }
            catch
            {
                MessageBox.Show("代理设置失败");
                return;
            }

            //激活代理设置
            try
            {
                SafeNativeMethods.InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
                SafeNativeMethods.InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
            }
            catch
            {
                MessageBox.Show("代理激活失败");
                return;
            }
        }

        private void ShowProxy()
        {
            //打开注册表
            RegistryKey regKey = Registry.CurrentUser;
            string SubKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
            RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);
            if (optionKey == null)
            {
                MessageBox.Show(@"注册表损坏，请修复\nHKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings");
                return;
            }

            //获取键值
            string EnableValue = "0";
            string ServerValue = "0";
            try
            {

                EnableValue = optionKey.GetValue("ProxyEnable").ToString();
                ServerValue = optionKey.GetValue("ProxyServer").ToString();
            }
            catch
            {

            }

            if (EnableValue == "1")
            {
                this.tbIPView.Text = ServerValue;
                this.ToolStripMenuItem_ViewProxy.Text = "当前：" + ServerValue;
                this.ToolStripMenuItem_ViewProxy2.Text = "当前：" + ServerValue;
                this.notifyIcon1.ShowBalloonTip(3000, "友情提示", "当前代理服务器：" + ServerValue, ToolTipIcon.Info);
            }
            else
            {
                this.tbIPView.Text = "代理已关闭";
                this.ToolStripMenuItem_ViewProxy.Text = "代理已关闭";
                this.ToolStripMenuItem_ViewProxy2.Text = "代理已关闭";
                this.notifyIcon1.ShowBalloonTip(3000, "友情提示", "代理功能已关闭", ToolTipIcon.Info);
            }
        }

        private bool ReadProxy(string ProxyServer)
        {
            string Status = "0";
            string Server = "";
            RegistryKey regKey = Registry.CurrentUser;
            string SubKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
            RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);
            if (optionKey == null)
            {
                MessageBox.Show(@"注册表损坏，请修复\nHKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings");
                return false;
            }

            try
            {
                Status = optionKey.GetValue("ProxyEnable").ToString();
            }
            catch
            {
                return false;
            }
            if (Status != "1") return false;
            try
            {
                Server = optionKey.GetValue("ProxyServer").ToString();
            }
            catch
            {
                return false;
            }
            if (ProxyServer == Server) return true;
            else return false;
        }

        #endregion

        #region ToolStripMenuItem

        private void ToolStripMenuItem_Option_Click(object sender, EventArgs e)
        {
            Option option = new Option();
            option.ShowInTaskbar = false;
            option.ShowDialog();
            InitForm();
        }

        private void ToolStripMenuItem_About_Click(object sender, EventArgs e)
        {
            MessageBox.Show("IE代理配置工具V1.0", "萍乡互通");
        }

        private void ToolStripMenuItem_TelCom_Click(object sender, EventArgs e)
        {
            btnTeleCom_Click(sender, e);
        }

        private void ToolStripMenuItem_UniCom_Click(object sender, EventArgs e)
        {
            btnUniCom_Click(sender, e);
        }

        private void ToolStripMenuItem_Show_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
        }

        private void ToolStripMenuItem_Exit_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("您确认要退出吗？", "友情提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                Application.Exit();
            }
        }

        #endregion

        #region Method

        public void InitForm()
        {
            #region GUI Parameter

            int LocationX = 35;
            int LocationY = 80;
            int FormX = 200;
            int FormY = 80;
            int StepX = 0;
            int StepY = 80;
            int i = 0;

            this.Width = FormX;
            this.Height = FormY;

            #endregion

            #region 读取注册表

            string ProxyStatus = null;
            string ProxyServer = null;

            RegistryKey regKey = Registry.CurrentUser;
            string SubKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
            RegistryKey optionKey = regKey.OpenSubKey(SubKeyPath, true);
            if (optionKey == null)
            {
                MessageBox.Show(@"注册表损坏，请修复\nHKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings");
                return;
            }
            try
            {
                ProxyStatus = optionKey.GetValue("ProxyEnable").ToString();
            }
            catch
            {
                ProxyStatus = "0";
            }
            try
            {
                ProxyServer = optionKey.GetValue("ProxyServer").ToString();
            }
            catch
            {
                if (ProxyStatus == "1")
                {
                    optionKey.SetValue("ProxyEnable", 0);
                    SafeNativeMethods.InternetSetOption(IntPtr.Zero, INTERNET_OPTION_REFRESH, IntPtr.Zero, 0);
                    SafeNativeMethods.InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SETTINGS_CHANGED, IntPtr.Zero, 0);
                    ProxyStatus = ProxyStatus = optionKey.GetValue("ProxyEnable").ToString();
                    MessageBox.Show("注册表异常，代理已关闭");
                }
                ProxyServer = "";
            }

            #endregion

            #region 初始电信配置

            string strTelName;
            string strTelEn;
            string strTelCom;
            string strTelPort;
            string TelText;

            if (!ProxyFile.ReadInivalue("TelCom", "Name", out strTelName))
            {
                strTelName = "电信代理";
            }
            if (!ProxyFile.ReadInivalue("TelCom", "Enable", out strTelEn))
            {
                strTelEn = "0";
            }
            if (!ProxyFile.ReadInivalue("TelCom", "Server", out strTelCom))
            {
                strTelCom = "";
            }
            if (!ProxyFile.ReadInivalue("TelCom", "Port", out strTelPort))
            {
                strTelPort = "";
            }
            if (strTelEn == "1")
            {
                this.btnTelCom.Location = new Point(LocationX + i * StepX, LocationY + i * StepY);
                i++;
                this.Width = FormX + i * StepX;
                this.Height = FormY + i * StepY;

                if (ProxyServer == (strTelCom + ":" + strTelPort) && ProxyStatus == "1")
                {
                    TelText = "关闭" + strTelName;
                }
                else
                {
                    TelText = "启用" + strTelName;
                }

                this.btnTelCom.Visible = true;
                this.ToolStripMenuItem_TelCom.Visible = true;
                this.btnTelCom.Text = TelText;
                this.ToolStripMenuItem_TelCom.Text = TelText;
            }
            else
            {
                this.btnTelCom.Visible = false;
                this.ToolStripMenuItem_TelCom.Visible = false;
            }

            #endregion

            #region 初始化联通配置

            string strUniName;
            string strUniEn;
            string strUniCom;
            string strUniPort;
            string UniText;

            if (!ProxyFile.ReadInivalue("UniCom", "Name", out strUniName))
            {
                strUniName = "联通代理";
            }
            if (!ProxyFile.ReadInivalue("UniCom", "Enable", out strUniEn))
            {
                strUniEn = "0";
            }
            if (!ProxyFile.ReadInivalue("UniCom", "Server", out strUniCom))
            {
                strUniCom = "";
            }
            if (!ProxyFile.ReadInivalue("UniCom", "Port", out strUniPort))
            {
                strUniPort = "";
            }
            if (strUniEn == "1")
            {
                this.btnUniCom.Location = new Point(LocationX + i * StepX, LocationY + i * StepY);
                i++;
                this.Width = FormX + i * StepX;
                this.Height = FormY + i * StepY;

                if (ProxyServer == (strUniCom + ":" + strUniPort) && ProxyStatus == "1")
                {
                    UniText = "关闭" + strUniName;
                }
                else
                {
                    UniText = "启用" + strUniName;
                }

                this.btnUniCom.Visible = true;
                this.ToolStripMenuItem_UniCom.Visible = true;
                this.btnUniCom.Text = UniText;
                this.ToolStripMenuItem_UniCom.Text = UniText;
            }
            else
            {
                this.btnUniCom.Visible = false;
                this.ToolStripMenuItem_UniCom.Visible = false;
            }

            #endregion

            #region 初始化过滤配置

            string FilterEn="";
            if (!ProxyFile.ReadInivalue("Filter", "Enable", out FilterEn))
            {
                FilterEn = "0";
            }
            if (FilterEn == "1")
            {
                if (!ProxyFile.ReadInivalue("Filter", "Regular", out GlobalAttrib.Filters))
                {
                    GlobalAttrib.Filters = "";
                }
            }

            #endregion
        }

        #endregion
    }

    [SuppressUnmanagedCodeSecurityAttribute]
    internal static class SafeNativeMethods
    {
        [DllImport(@"wininet", SetLastError = true, CharSet = CharSet.Auto, EntryPoint = "InternetSetOption", CallingConvention = CallingConvention.StdCall)]
        public static extern bool InternetSetOption(IntPtr hInternet, int dmOption, IntPtr lpBuffer, int dwBufferLength);

        [DllImport("user32")]
        public static extern bool AnimateWindow(IntPtr hwnd, int dwTime, int dwFlags);
    }
}
